package com.itheima.test;

import java.util.InputMismatchException;
import java.util.Scanner;

public class Demo1 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        double num1 = 0, num2 = 0;
        String operator = "";
        boolean inputValid = false;

        // 输入第一个数字
        while (!inputValid) {
            try {
                System.out.print("请输入第一个数字: ");
                num1 = scanner.nextDouble();
                inputValid = true;
            } catch (InputMismatchException e) {
                System.out.println("输入错误，请输入有效的数字！");
                scanner.nextLine(); // 清除无效输入
            }
        }

        // 输入运算符
        inputValid = false;
        while (!inputValid) {
            System.out.print("请输入运算符 (+, -, *, /): ");
            operator = scanner.next();
            if (operator.matches("[+\\-*/]")) {
                inputValid = true;
            } else {
                System.out.println("无效运算符，请重新输入！");
            }
        }

        // 输入第二个数字
        inputValid = false;
        while (!inputValid) {
            try {
                System.out.print("请输入第二个数字: ");
                num2 = scanner.nextDouble();
                inputValid = true;
            } catch (InputMismatchException e) {
                System.out.println("输入错误，请输入有效的数字！");
                scanner.nextLine(); // 清除无效输入
            }
        }

        // 计算并输出结果
        double result = 0;
        boolean calculationValid = true;

        switch (operator) {
            case "+":
                result = num1 + num2;
                break;
            case "-":
                result = num1 - num2;
                break;
            case "*":
                result = num1 * num2;
                break;
            case "/":
                if (num2 == 0) {
                    System.out.println("错误：除数不能为零");
                    calculationValid = false;
                } else {
                    result = num1 / num2;
                }
                break;
        }

        if (calculationValid) {
            System.out.printf("计算结果: %.2f\n", result);
        }

        scanner.close();
    }
}